#region Namespace
using PHSRAG.Insight21.Context;
using PHSRAG.Security.Enumerations;
using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
using PHSRAG.Insight21.SearchContext;
using System.ComponentModel;
#endregion

namespace PHSRAG.Insight21.COI
{	/// <summary>
	///		This user control allows the logged in user(with Super-User access rights) to impersonate as other supervisors or reviewers in the system.
	/// </summary>
	public partial class UserImpersonation : System.Web.UI.UserControl
	{
		#region custom event
		/// <summary>Custom event that is made public to be captured in the pages consuming the control </summary>
		public event EventHandler ImpersonateClicked;
		/// <summary>Custom event that is made public to be captured in the pages consuming the control </summary>
		public event EventHandler FindSupervisorsClicked;
		#endregion

		#region Instance variables (Private )
		//cachePolicy
		private Policy.ICachePolicy	cachePolicy;
		//Page cache policy
		private Policy.ICachePolicy	pageCachePolicy;
		#endregion

		#region Event Handlers
		/// <summary>
		/// The page load event handler
		/// </summary>
		/// <param name="sender">Sender,that raised the event</param>
		/// <param name="e">argiments related to the sender</param>		
		protected void OnPageLoad(object sender, System.EventArgs e)
		{
			try
			{
				Hashtable incomingPageHash = 
					cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
				if (incomingPageHash != null && !IsPostBack)
				{
					if (incomingPageHash.ContainsKey(Keys.ImpersonationIdKey))
					{
						if (((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId != Convert.ToInt32(incomingPageHash[Keys.ImpersonationIdKey]))
						{
							LoadDropDownList(Convert.ToInt32(incomingPageHash[Keys.ImpersonationIdKey]));
						}
					}											
				}	
			}
			catch(Exception ex)
			{
				Utility.ExceptionReport.WriteToEventLog("Error occurred while trying to load the user control.Error occured at UserImpersonation.OnPageLoad())",ex,true,Utility.ExceptionReport.ReportType.Error);
			}
		}
		
		/// <summary>
		/// Event handler for Find Supervisors button click
		/// </summary>
		/// <param name="sender">Sender,that raised the event</param>
		/// <param name="e">argiments related to the sender</param>	
		private void OnFindSupervisors(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			//Raise the public event
			if (FindSupervisorsClicked != null)
				FindSupervisorsClicked(sender, e);
			LoadDropDownList(0);
		}

		/// <summary>
		/// Event handler for Impersonate button click.
		/// Note:This will inturn raise a public event which will be captured in the base page(hierarchy maintenance page) to reload the grid.
		/// </summary>
		/// <param name="sender">Sender,that raised the event</param>
		/// <param name="e">argiments related to the sender</param>	
		private void OnImpersonate(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				Hashtable outgoingData = new Hashtable();
				if (impersonatedUserList.SelectedValue != "-1")
				{					
					outgoingData.Add(Keys.ImpersonationIdKey, Convert.ToInt32(impersonatedUserList.SelectedValue));
					pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
					//Raise the public event
					if (ImpersonateClicked != null)
						ImpersonateClicked(sender, e);
				}
			}
			catch(Exception ex)
			{
				Utility.ExceptionReport.WriteToEventLog("Error occurred while trying to impersonate.Error occured at UserImpersonation.OnImpersonate())",ex,true,Utility.ExceptionReport.ReportType.Error);
			}
		}		

		/// <summary>
		/// This method will capture the public event hosted by the base page.
		/// </summary>
		/// <param name="sender">Sender,that raised the event</param>
		/// <param name="e">argiments related to the sender</param>	
		public void ResetDropDownSelection(object sender, System.EventArgs e)
		{
			try
			{				
				impersonatedUserList.SelectedValue="-1";
			}
			catch(Exception ex)
			{
				Utility.ExceptionReport.WriteToEventLog("Error occurred while trying to reset the dropdown list selection.Error occured at UserImpersonation.ResetDropDownSelection())",ex,true,Utility.ExceptionReport.ReportType.Error);
			}
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
			pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.findSupervisors.Click += new System.Web.UI.ImageClickEventHandler(OnFindSupervisors);
			this.showImpersonatedUserHierarchy.Click += new System.Web.UI.ImageClickEventHandler(OnImpersonate);
			this.Load += new System.EventHandler(this.OnPageLoad);

		}
		#endregion

		#region private methods
		/// <summary>
		/// This method will populate the dropdown with the list of supervisor and reviewers available in the system.
		/// If Selected value(parameter) is zero or the logged in user then seletecd index is set to zero(0)
		/// </summary>
		/// <param name="selectValue">Value that sets the selected item in the dropdown.</param>
	
		private void LoadDropDownList(int selectValue)
		{
			try
			{
				CommonSearchContext searchContext = (CommonSearchContext)cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
				
				DataTable dt=null;				
					 dt =COIUserSummary.GetSupervisorsForImpersonation(Utility.DataAccess.ConnectionString,
						((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId,
						 searchContext.GetSearchCriteria(Page.Request.Url.ToString()),(IsPostBack)? true:false);
						
			
				if (dt.Rows.Count>0)
				{
					DataRow dr=dt.NewRow();
					dr["PersonId"]=-1;
					dr["Name"]="--Select--";
					dt.Rows.InsertAt(dr,0);
					impersonatedUserList.DataSource=dt;
					impersonatedUserList.DataTextField="Name";
					impersonatedUserList.DataValueField="PersonId";
					impersonatedUserList.DataBind();	
					impersonatedUserList.SelectedValue=(selectValue == 0 || selectValue == ((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId)? "-1": Convert.ToString(selectValue);
				
				}
				else
				{
					impersonatedUserList.DataSource=dt;
					impersonatedUserList.DataTextField="Name";
					impersonatedUserList.DataValueField="PersonId";
					impersonatedUserList.DataBind();	
				}
			}
			catch(Exception ex)
			{
				Utility.ExceptionReport.WriteToEventLog("Error occurred while trying to load the supervisor to the dropdown.Error occured at UserImpersonation.LoadDropDownList())",ex,true,Utility.ExceptionReport.ReportType.Error);
			}

		}
		#endregion

        #region Properties

        [Bindable(true), Category("Other"), Description("Full name of the selected user.")]
        public string SelectedUserName
        {
            get
            {
                return impersonatedUserList.SelectedItem != null ? impersonatedUserList.SelectedItem.Text : null;
            }
        }

        #endregion
    }
}
